﻿using Examination.Args;
using Examination.Args.Request;
using Examination.Model;
using Examination.Utils;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mime;
using System.Threading.Tasks;

namespace Examination.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class LoginController : ControllerBase
    {
        private readonly DataContext _dataContext;

        public LoginController(DataContext dataContext) => _dataContext = dataContext;

        [HttpPost]
        public async Task<IActionResult> Login([FromBody] LoginParameter parameter)
        {
            //var users = await _dataContext.Users.ToListAsync();
            //for (int i = 0; i < users.Count; i++)
            //{
            //    users[i].Password = MD5Helper.GenerateMD5(users[i].Password);
            //}
            //_dataContext.Users.UpdateRange(users);
            //await _dataContext.SaveChangesAsync();
            parameter.Password = MD5Helper.GenerateMD5(parameter.Password);
            User user = await _dataContext.Users.FirstOrDefaultAsync(u => u.Number == parameter.Number && u.Password == parameter.Password);
            if (user == null)
            {
                return new JsonResult(new ResponseData() { Status = 1, Msg = "用户名或密码错误" });
            }
            else if (!parameter.Code.Equals(Request.HttpContext.Session.GetString("code")?.ToLower()))
            {
                return new JsonResult(new ResponseData() { Status = 1, Msg = "验证码错误" });
            }
            else
            {
                Request.HttpContext.Session.SetString("userId", user.Id.ToString());
                return new JsonResult(new ResponseData());
            }
        }

        [HttpPost]
        public IActionResult LoginOut()
        {
            Request.HttpContext.Session.SetString("userId", "");
            return new JsonResult(new ResponseData());
        }

        [HttpPost]
        public async Task<IActionResult> Register([FromBody] RegisterParameter parameter)
        {
            if (!parameter.Code.ToLower().Equals(Request.HttpContext.Session.GetString("code")?.ToLower()))
            {
                return new JsonResult(new ResponseData() { Status = 1, Msg = "验证码错误" });
            }
            if (await _dataContext.Users.CountAsync(u => u.Number.Equals(parameter.Number)) > 0)
            {
                return new JsonResult(new ResponseData() { Status = 1, Msg = $"注册失败，学号{parameter.Number}已存在" });
            }
            User user = new User()
            {
                Name = parameter.Name,
                Number = parameter.Number,
                Class = parameter.Class.Trim(),
                Password = MD5Helper.GenerateMD5(MD5Helper.GenerateMD5(parameter.Number.Substring(6)))
        };
            await _dataContext.Users.AddAsync(user);
            await _dataContext.SaveChangesAsync();
            return new JsonResult(new ResponseData());
        }

        [HttpGet]
        public async Task<IActionResult> Captcha([FromServices] ICaptcha _captcha)
        {
            string code = await _captcha.GenerateRandomCaptchaAsync();
            CaptchaResult result = await _captcha.GenerateCaptchaImageAsync(code);
            Request.HttpContext.Session.SetString("code", code);
            return File(result.CaptchaMemoryStream.ToArray(), "image/png");
        }
    }
}
